package com.github.weixin.demo.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.weixin.demo.persistence.dao.DeviceAttributeDao;
import com.github.weixin.demo.persistence.dao.GetQRCodeResultDao;
import com.github.weixin.demo.persistence.entity.DeviceAttribute;
import com.github.weixin.demo.persistence.entity.GetQRCodeResult;
import com.google.common.collect.Lists;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpDeviceService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.device.BaseResp;
import me.chanjar.weixin.mp.bean.device.WxDevice;
import me.chanjar.weixin.mp.bean.device.WxDeviceAuthorize;
import me.chanjar.weixin.mp.bean.device.WxDeviceAuthorizeResult;
import me.chanjar.weixin.mp.bean.device.WxDeviceQrCodeResult;

@RestController
@RequestMapping(value="/api/biz")
public class ApiController{   
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired GetQRCodeResultDao qrcdao;
	@Autowired DeviceAttributeDao dad;
	@Autowired
    protected WxMpService wxMpService;
	@Value("#{deviceProperties.productId}")
	String productId;
	WxMpDeviceService deviceService;
	@RequestMapping(value="/getqr")
	public Object getQR() throws WxErrorException{
		logger.info(" Registered product id is {}",productId);
		WxDeviceQrCodeResult res = deviceService.getQrCode(productId);
		if(res.getBaseResp().getErrCode() == 0){
			GetQRCodeResult gqrcr = new GetQRCodeResult(res.getDeviceId(), res.getQrTicket());
			qrcdao.save(gqrcr);
		}
		return res;
	}
	
	@RequestMapping(value="/devicelist")
	public Object deviceList() throws WxErrorException{
		
		Object result = qrcdao.findAll();
		logger.info("query result:{}" , result);
		return result;
	}
	
	@RequestMapping(value="/querydeviceatt")
	public Object queryDeviceAtt() throws WxErrorException{
		return null;
	}
	
	@RequestMapping(value="/authdev")
	public Object authDev(HttpServletRequest req) throws WxErrorException{
		logger.info(" Registered product id is {}",productId);
		WxDeviceAuthorize wda = new WxDeviceAuthorize();
		wda.setDeviceNum("1");
		wda.setProductId(productId);
		wda.setOpType(att(req,"op_type"));
		WxDevice wd = new WxDevice();
		
		wd.setId(att(req,"id"));
		wd.setMac(att(req,"mac"));
		wd.setConnectProtocol(att(req,"connect_protocol"));
		wd.setAuthKey(att(req,"authKey"));
		wd.setCloseStrategy(att(req,"close_strategy"));
		wd.setConnStrategy(att(req,"conn_strategy"));
		wd.setCryptMethod(att(req,"crypt_method"));
		wd.setAuthVer(att(req,"auth_ver"));
		wd.setManuMacPos(att(req,"manu_mac_pos"));
		wd.setSerMacPos(att(req,"ser_mac_pos"));
		wda.addDevice(wd);
		WxDeviceAuthorizeResult res = deviceService.authorize(wda);
		List<DeviceAttribute> resSave = Lists.newArrayList();
		//FIXME:前台有多个设备时要记得修正
		for(BaseResp br : res.getResp()){
			if(br.getErrCode() == 0){
				resSave.add(new DeviceAttribute(wd.getId(), wd.getMac(), wd.getConnectProtocol(), wd.getCloseStrategy(), wd.getConnectProtocol(), wd.getCryptMethod(), wd.getAuthVer(), wd.getManuMacPos(), wd.getSerMacPos(), wd.getBleSimpleProtocol()));
			}
		}
		dad.save(resSave);
		return res;
	}
	
	public String att(HttpServletRequest req,String name){
		String res = req.getParameter(name);
		return StringUtils.isEmpty(res)? (String)req.getAttribute(name):res;
		
	}
	
	@RequestMapping(value="/reg")
	public Object views(HttpServletRequest req,HttpServletResponse res){
		ArrayList<String> re = new ArrayList<String>();
		String macAddr = req.getParameter("mac");
		//WxDeviceBind wdb;
		//deviceService.bind(wxDeviceBind);
		re.add(macAddr);
		return re;
	}
	@PostConstruct
	private void INIT(){
		logger.info("inject device service");
		this.deviceService = wxMpService.getDeviceService();
	}
//	@Override
//	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//		// TODO Auto-generated method stub
//		
//		return this;
//	}
//
//	@Override
//	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//		// TODO Auto-generated method stub
//		this.deviceService = wxMpService.getDeviceService();
//		logger.info("inject device service");
//		return this;
//	}

}
